import 'dart:convert';
import 'package:get/get.dart';
import 'package:personinfo/model/home/UserModel.dart';
import 'package:shared_preferences/shared_preferences.dart';

class AppController extends GetxController{
  static AppController get to => Get.find();

  late SharedPreferences _prefs; // 需要在使用前初始化
  final Rx<UserModel?> _user = Rx(null);
  UserModel? get user => _user.value;
  bool get isLogin => user?.isLoggedIn ?? false;

  var tabIndex = 0;

  @override
  void onInit() async {
    super.onInit();
    _prefs = await SharedPreferences.getInstance(); // 初始化 _prefs
    _loadUserFromPrefs();
  }

  // 从本地加载用户
  Future<void> _loadUserFromPrefs() async {
    final String? userData = _prefs.getString('user');
    if (userData != null) {
      try {
        final Map<String, dynamic> json = Map<String, dynamic>.from(jsonDecode(userData));
        _user.value = UserModel.fromJson(json);
      } catch (e) {
        // 解析失败，清除无效数据
        await _prefs.remove('user');
      }
    }
    update();
  }

  // 登录成功后保存用户
  Future<void> login(String token, {String? name, int? id, String ? password}) async {
    final user = UserModel(token: token, name: name, id: id, password: password);
    _user.value = user;

    // 保存到本地
    final String userData = jsonEncode(user.toJson());
    await _prefs.setString('user', userData);

    update();
  }

  // 退出登录
  Future<void> logout() async {
    _user.value = null;
    await _prefs.remove('user');
    update();
  }

  setTabIndex(index){
    tabIndex = index;
    update();
  }
}
